/**
 * @file 厂商单工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 */

var dependsList = [
    'index', 'layer', 'form', 'table', '$http',
    'laydate', 'util', 'zmn_validate', 'zmnUtils','select2',
    'validator', 'Vue', 'dayjs'
];

layui.define(dependsList, function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var validate = layui.zmn_validate;
    var util = layui.util;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var Vue = layui.Vue;
    var dayjs = layui.dayjs;
    var table = layui.table;
    var select2;
    var countyData = [];

    window.EventBus = new Vue();

    var orderPostTable;

    var objOfURL = {
        workDetail: '/work/detail.action',
        workModifyDetail: '/work/modify/detail.action'
    };

    var options = {
        saveURL: null,
        isNew: false,
        modifyDetail: false,
        success: () => {}
    };

    // 城市
    var cityData = {};

    var NORMAL_ORDER_ADD_URL = '/order/normal/add.action';

    // 获取省份、城市、区域
    var CITY_URL = '/area/permit/city/list.action';
    var COUNTY_URL = '/area/list.action';
    var AREA_DETAIL_URL = '/area/detail/list.action';
    // 根据经纬度获取区域信息
    var AREA_INFO_URL = "/area/getAreaInfo.action";

    // 获取产品列表
    var PRODUCT_URL = '/serv/product/list.action';
    // 获取产品服务类型
    var PRODUCT_SERV_URL = '/serv/factory/product/servCateg/list.action';
    // 获取常见故障
    var PRODUCT_SUBSIDIARY_URL = '/serv/factory/product/subsidiary/list.action';
    // 订单产品转化
    var CONVERT_PRODUCT_URL = '/serv/factory/product/convertProduct.action';
    // 厂商渠道转化
    var CONVERT_CHANNEL_ID_URL = '/channel/getChannelIdByFactoryId.action';

    // 获取小区地址信息
    var COMMUNITY_ADDRESS_URL = '/area/queryCommunity.action';
    // 百度地图地址联想
    var BAIDU_MAP_SUGGESTED = "//api.map.baidu.com/place/v2/suggestion";

    // 校验地址是否在服务范围
    var STREET_VALIDATION_URL = '/area/checkServicePoint.action';

    // 检查返修单源单号
    var CHECK_REWORD_ID_URL = '/order/check/rework.action';

    // 产品几个表页面地址
    var PRODUCT_PRICE_TABLE_URL = '/order/getProductPriceTable';

    // 获取公司信息
    var COMPANY_URL = '/company/getCompanyName.action';

	// 获取默认预约时间
	var GET_DEFAULT_DUTYTIME = '/schedule/defaulttime.action';
    // 根据渠道、城市、产品类型获取服务分类
    var GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL = '/serv/category/listByCityIdAndChannelIdAndShowType.action';
    // 获取工单类型以及默认服务项信息
    var GET_SERVITEM_TYPE_INFO_WORK_URL = '/order/getServItemTypeAndInfo.action';
    // 根据关键字获取厂商配件
    var GET_FACTORY_PARTS_URL = '/serv/factory/getParts.action';
    // 检查是否平台直派
    var IS_GRID = '/common/check/grid.action';

    let servCategoryCache = {}

    // 工单类型枚举
    var ORDER_TYPE_ENUM = {
        'NEW': '1',
        'REWORK': '2'
    };

    // select选择框工作流
    let productNode = {
        name: 'product',
        child: [$("#servCategoryId"), $("#productId")],
        next:undefined
    };
    let addressNode = {
        name: 'address',
        child:[$("#servCategoryId"), $("#productId")],
        next: productNode
    };
    let factoryNode = {
        name: 'factory',
        child:$(".address").find("select"),
        next: addressNode
    };

    let newMachineTableId = 'newMachineTable';
    let factoryPartTableId = 'factoryPartTable';

    /**
     * 远程获取产品数据
     * @param factoryId 厂商 id
     * @param cb 回调函数
     */
    function fetchProductData(plat, channelId, cityId, servCategId, bizType, cb) {
        return $http.get(PRODUCT_URL, { plat: plat, channelId: channelId, cityId: cityId, servCategId: servCategId, productShowType: 1, bizType: bizType });
    }

    /**
     * 远程获取产品服务类型数据
     * @param fcProductId 厂商 id
     * @param cb 回调函数
     */
    function fetchProductServData(fcProductId, cb) {
        return $http.get(PRODUCT_SERV_URL, { fcProductId: fcProductId });
    }

    /**
     * 获取服务故障
     * @param {string | number} productId 产品id
     * @param {function} cb 回调函数
     */
    function fetchProductSubsidiary (productId) {
        return $http.$get(PRODUCT_SUBSIDIARY_URL, { productId: productId});
    }

    /**
     * 厂商产品转化为基础产品
     * @param {string | number} productId 产品id
     * @param {function} cb 回调函数
     */
	function fetchToProduct (plat, fcProductId, servCategoryId, channelId) {
		return $http.$get(CONVERT_PRODUCT_URL, {plat: plat, fcProductId: fcProductId, servCategId: servCategoryId, channelId: channelId})
    }

    /**
     * 厂商产品转化为基础产品
     * @param {string | number} productId 产品id
     * @param {function} cb 回调函数
     */
	function fetchChannelId (factoryId) {
		return $http.$get(CONVERT_CHANNEL_ID_URL, {factoryId: factoryId})
    }

    /**
     * 根据父级 id 远程获取下级区域数据
     * @param {string} url 地址
     * @param {object} params 参数
     */
    function fetchAreaDataByParentId (url, params) {
        return $http.get(url, params).then(function (data) {
            return data;
        }, function () {
            layer.msg('获取数据失败');
            return $.Deferred().resolve([]);
        });
    }

    /**
     * 根据省份 id 远程获取城市数据
     * @param provinceId 城市 id
     */
    function fetchCityData (provinceId) {
        return fetchAreaDataByParentId(CITY_URL, {
            provinceId: provinceId,
            channelId: getters.getChannelId(),
            showType: 1,
        });
    }

    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaData (cityId) {
        return fetchAreaDataByParentId(COUNTY_URL, { parentId: cityId });
    }

    /**
     * 根据经纬度 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaInfo (lon, lat) {
        return fetchAreaDataByParentId(AREA_INFO_URL, { longitude: lon, latitude: lat });
    }

    /**
     * 获取区县信息查询
     */
    function getCountyInfo(countyName) {
        if (!countyName) {
            return null;
        }

        if(countyData.length == 0){
            $('#county-list').find('span').each(function () {
                var county = {
                    countyId: $(this).data('id'),
                    countyName: $(this).text(),
                };
                countyData.push(county);
            });
        }

        for (var i = 0; i < countyData.length; i++) {
            if (countyName == countyData[i].countyName) {
                return countyData[i];
            }
        }
        return null;
    }

    /**
     * 区县信息查询
     */
    function setCountyInfo(countyName, lng, lat, callback) {
        var cityId = $('#cityId option:selected').val();
        // 本地数据获取countyinfo
        countyName = countyName || '';
        let countyInfo = getCountyInfo(countyName);
        if (countyInfo) {
            updateAreaInfo(countyInfo.countyId);
            if(callback){
                callback(countyInfo.countyId);
            }
            return;
        }

        // 调用远程接口获取countyinfo
        fetchAreaInfo(lng,lat).then(function (data) {
            if (cityId != data.cityId) {
                switchCity(data.cityId);
            }

            updateAreaInfo(data.countyId);
            if(callback){
                callback(data.countyId);
            }
        }, function (msg) {
            layer.msg(msg);
        });
    }

    /**
     * 获取小区库的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchSuggestedStreet (params, cb) {
        fetchBaiduSuggestedStreet(params, cb);
        // $.ajax({
        //     type: "get",
        //     url: COMMUNITY_ADDRESS_URL,
        //     data: params,
        //     success: function (resultData) {
        //         if (resultData.statusBool) {
        //             if (resultData.data === undefined) {
        //                 resultData.data = [];
        //             }
        //             var data = resultData.data;
        //             // 过滤搜索结果
        //             data = data.filter((item) => {
        //                 if(!item.location){
        //                     return false;
        //                 }
        //                 return !item.city || item.city.indexOf(params.cityName.slice(0, 1)) !== -1;
        //             });
        //             cb(data);
        //         } else {
        //             console.log(params, resultData.message);
        //             // 异常，调用百度地址
        //             fetchBaiduSuggestedStreet(params, cb);
        //         }
        //     },
        //     error: function () {
        //         // 异常，调用百度地址
        //         fetchBaiduSuggestedStreet(params, cb);
        //     },
        // });
    }

    /**
     * 获取百度联想出的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchBaiduSuggestedStreet(params, cb) {
        $.ajax({
            url: BAIDU_MAP_SUGGESTED,
            type: "GET",
            dataType: "jsonp",
            data: {
                query: params.queryStr,
                region: params.cityName,
                city_limit: true,
                output: "json",
                ak: params.ak,
            },
            success: function (response) {
                if (response.status === 0) {
                    // 过滤搜索结果
                    var data = response.result.filter((item) => {
                        if ( item.name == item.province || item.name == item.city || item.name == item.district || item.name.endsWith('-道路') || item.name.endsWith('镇') || item.name.endsWith('乡')) {
                            return false;
                        }
                        return (item.city.indexOf(params.cityName.slice(0, 1)) !== -1 ) || (!item.city && item.district.indexOf(params.cityName.slice(0, 1)) !== -1);
                    });
                    cb(data);
                }
            },
        });
    }

    /**
     * 获取厂商对应的渠道ID
     */
    function initChannelId(cb) {
        fetchChannelId(getters.getFactoryId()).then(function (data) {
            $("#channelId").val(data);
            if(cb){
                cb();
            }
        }, function (msg) {
            layer.msg('无法获取厂商对应的ID');
            $("#channelId").val('');
        })
    }

	function initDutyTime (callback) {
		if(!options.isNew){
            if (callback) callback();
			return;
		}

        if (!getters.getProductId()) {
            if (callback) callback();
            return;
        }

		$http.$get(GET_DEFAULT_DUTYTIME, {
			plat:getters.getPlat(),
			platWork:getters.getPlatWork(),
			channelId: getters.getChannelId(),
			cityId: getters.getCityId(),
			productId: getters.getProductId(),
			type:getters.getOrderType(),
            dutyTime:getters.getDutyTime()
		}).then(function (data) {
			initDutyTimeInfo(data.showDutyTime,data.dutyTime);
            if (callback) callback();
		}, function (msg) {
			layer.msg('获取默认时间失败');
			initDutyTimeInfo('','');
            if (callback) callback();
		});
	}

    /**
     * 保存新订单
     * @param {object} params 订单信息
     * @param {function} cb 回调函数
     */
    function saveOrderInfo (params, btn) {
        // 移除禁用标示
        $('select,input').attr("disabled", false);

        return $http.lockSave(options.saveURL, params, btn);
    }

    function getLayuiSelectValue (selector) {
        return $(selector + ' option:selected').val();
    }

    function getLayuiSelectText(selector) {
        return $(selector + " option:selected").text();
    }

    /**
     * 全局获取器
     * @type {{getCityId: (function(): jQuery)}}
     */
    var getters = {
        getInputValueById: function (id) {
            return $.trim($('#' + id).val());
        },
        getLocation: function () {
            return {
                lng: $('#longitude').val(),
                lat: $('#latitude').val()
            };
        },
        getPlat: function () {
            return $('#plat').val() || plat;
        },
        getCityId: function () {
            return getLayuiSelectValue('#cityId');
        },
        getTelephone: function () {
            return this.getInputValueById('telephone');
        },
        getCountyId: function () {
            return getLayuiSelectValue('#countyId');
        },
        getInputCountyName: function () {
            let countyId = this.getCountyId();
            if(!countyId) return "";
            return $('#county-list').find('span[data-id='+countyId+']').text();
        },
        getStreetId: function () {
            return getLayuiSelectValue('#streetId');
        },
        getCityName: function () {
            return $('#cityId option:selected').text();
        },
        getStreet: function () {
            return $('#customerAddress').val();
        },
        getStreetSource: function () {
            return $('#streetSource').val() || 0;
        },
        getServCategId: function () {
            return getLayuiSelectValue('#servCategoryId');
        },
        getFcProductId: function () {
            return getLayuiSelectValue('#fcProductId');
        },
        getProductId: function () {
            return $('#productId').val();
        },
        getProductShowType: function () {
            return 1;
        },
        getProvinceId: function () {
            return getLayuiSelectValue('#provinceId');
        },
        getFactoryId: function () {
            return getLayuiSelectValue('#factoryId');
        },
        getBizType: function () {
            return $('#bizType:checked').val();
        },
        getDutyTime: function () {
            return $('#duty-time-input').val();
        },
        getWorkId: function () {
            return $('#work-id').val();
        },
        getOrderId: function () {
            return $('#order-id').val();
        },
        getCount: function () {
            var count  = $('#count').val();
            return Number.parseInt(count) || 0;
        },
        checkServicePoint: function () {
            var checkServicePoint  = $('#checkServicePoint').val();
            return checkServicePoint === 'true';
        },
        getOrderType: function () {
            return this.getInputValueById('type');
        },
        getPlatWork: function () {
            return $('#platWork').val() || $('#plat').val() || platMark.YEYX;
        },
        getLongitude: function () {
            return $('#longitude').val();
        },
        getLatitude: function () {
            return $('#latitude').val();
        },
        getAddress: function () {
            return $('input[name="address"]').val();
        },
		getChannelId: function () {
            return $('input[name="channelId"]').val();
		},
        getBrandId: function () {
            return getLayuiSelectValue('#brand') || 1051;
        }
    };

    /**
     * 初始化产品数量输入框
     * @param {string} value 产品数量
     */
    function initCountInput (value) {
        $('#count').val(value);
    }

    /**
     * 初始化产品数量
     * @param {string} text 产品单位
     */
    function initProductUnit (text) {
        $('#unit').text(text);
    }


    /**
     * 渲染服务类型选择下拉框
     */
    function renderServCategorySelect(callback) {
        var cityId = getters.getCityId();
        var channelId = getters.getChannelId();
        var servCategId = getters.getServCategId();
        var showType = getters.getProductShowType();
        if (!cityId || !channelId) {
            return;
        }

        var cacheKey = cityId + '-' + channelId + '-' + showType;
        if (servCategoryCache[cacheKey]) {
            renderSelect('#servCategoryId', servCategoryCache[cacheKey], servCategId);
            // 加载产品
            if(callback){
                callback();
            }
        } else {
            $.getJSON(GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL,
                {
                    channelId: channelId,
                    cityId: cityId,
                    showType: showType
                },
                function (rsp) {
                    if (rsp.status === 200) {
                        servCategoryData = rsp.data;
                        servCategoryCache[cacheKey] = servCategoryData;
                        renderSelect('#servCategoryId', servCategoryData, servCategId);
                    } else {
                        renderSelect('#servCategoryId', []);
                    }
                    // 加载产品
                    if(callback){
                        callback();
                    }
                });
        }
    }


    /**
     * 初始化常见故障多选框组
     * @param {string} productId 产品id
     */
	function initProduct (plat, channelId, cityId, servCategId, bizType) {
		if (plat && channelId && cityId) {
		    let productId = getters.getProductId();
			fetchProductData(plat, channelId, cityId, servCategId, bizType).then(function (data) {
				renderSelect('#productId', data, parseInt(productId));
			}, function (msg) {
				layer.msg(msg)
			})
        } else {
            renderSelect('#productId', [], parseInt(productId));
        }
    }

    /**
     * 渲染常见错误多选框组
     * @param data 下拉框数据
     */
    function renderFaultsCheckboxGroup(data) {
        var htmlStr = '';
        var $faultsGroup = $('#faults-wrapper');
        var $faultsRow = $faultsGroup.closest('.layui-form-item');

        $.each(data, function (index, item) {
            htmlStr += '<input type="checkbox" lay-skin="primary" name="faultIdList" title="' + item.text + '" value="' + item.value + '" >';
        });

        $faultsGroup.html(htmlStr);

        if (data.length) {
            $faultsRow.show();
        } else {
            $faultsRow.hide();
        }

        form.render('checkbox');
    }

    /**
     * 初始化常见故障多选框组
     * @param {string} productId 产品id
     */
    function initCommonFaultsCheckboxGroup(productId) {
        if (!productId) {
            renderFaultsCheckboxGroup([]);
        } else {
            fetchProductSubsidiary(productId).then(function (data) {
                renderFaultsCheckboxGroup(data);
            })
        }
    }

    /**
     * 初始化其他故障文本框
     * @param {string} value 初始值
     */
    function initOtherFaultsTextarea (value) {
        $('#fault-remark').val(value);
    }

    /**
     * 更新下拉框选项的状态。1. 当前元素不可点击 2. 其余可以选项可以点击
     * @param elem select dom 元素
     */
    function updateOptionsStatus (elem) {
        $(elem).find('option')
        .attr("disabled", false)
        .filter(':selected')
        .attr("disabled", true);

        form.render('select');
    }

    /**
     * 渲染下拉选择框
     * @param el
     * @param data 下拉框数据
     * @param defaultVal 默认值
     */
    function renderSelect (el, data, defaultValue) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function (index, item) {
            htmlStr += '<option value="' + item.value + '" ' + (item.value == defaultValue ? ' selected ' : '') + 'data-pid="'+ item.pid +'">' + item.text + '</option>'
        });

        $(el).html(htmlStr);
        form.render('select');
    }

    /**
     * 渲染城市选择下拉框
     * @param {array} data 城市数据
     */
    function renderCitySelect (data) {
        var htmlStr = '<option value=""></option>';
        var oldCityId = getters.getCityId();

        $.each(data, function (index, item) {
            htmlStr += '<option value="' + item.value +
                '" data-pid="' + item.pid + '" ' +
                (oldCityId == item.value ? 'selected ' : ' ') +
                '>' + item.text + '</option>';
        });

        $('#cityId').html(htmlStr);
        form.render('select');
    }

    /**
     * 渲染城市选择下拉框
     * @param provinceId 省份ID
     */
    function initCitySelect (provinceId, channelId, cb) {
        if(!channelId){
            renderCitySelect([]);
            return;
        }

        var key = provinceId;
        if (options.isNew) {
            key = (provinceId || 0) + '-' + channelId;
        } else {
            // provinceId 为空时执行
            if (!provinceId) {
                renderCitySelect(json.cityList);
                if(cb){
                    cb();
                }
                return;
            }
        }

        if (cityData[key]) {
            renderCitySelect(cityData[key]);
        } else {
            fetchCityData(provinceId).done(function (data) {
                cityData[key] = data;
                renderCitySelect(data);
                if(cb){
                    cb();
                }
            });
        }
    }

    /**
     * 初始化服务区域显示
     * @param {array} data 服务区域列表
     */
    function renderServiceArea(data, cb) {
        var htmlStr = '';
        countyData = [];
        $.each(data, function (index, county) {
            if(!county.disabled){
                htmlStr += `<span class="county" data-id="${county.value}" data-name="${county.text}">${county.text}</span>`;
                countyData.push({
                    countyId: county.value,
                    countyName: county.text
                })
            }
        });

        var $serviceArea = $('#county-list');

        $serviceArea.html(htmlStr);

        var $countyId = $('#countyId');
        var optionHtmlStr = '<option value="">请选择区县</option>';

        var countyId = $countyId.val();

        $.each(data, function (index, county) {
            if(!county.disabled){
                if (countyId && county.value == countyId) {
                    optionHtmlStr += `<option value="${county.value}" selected="selected">${county.text}</option>`;
                } else {
                    optionHtmlStr += `<option value="${county.value}">${county.text}</option>`;
                }
            }
        });

        $countyId.html(optionHtmlStr);
        form.render('select');

        if (data.length) {
            $serviceArea.show();
        } else {
            $serviceArea.hide();
        }

        if (typeof cb === 'function') {
            cb();
        }
    }

    /**
     * 初始化服务区域显示
     */
    function initServiceArea (cityId, cb) {
        var cityId = cityId || getters.getCityId();

        if (!cityId) {
            renderServiceArea([]);
            return;
        }

        fetchAreaData(cityId).done(function (data) {
            renderServiceArea(data, cb);
        });
    }

    /**
     *  生成街道地址下拉框列表项
     * @param {Object} data 街道地址数据
     * @returns {string}
     */
    function createfetchSuggestedItemHtmlStr (data) {
        data.district = data.district || '';
        return '<li data-lng="' + data.location.lng +
            '" data-lat="' + data.location.lat +
            '" data-communityid="' + (data.communityId || 999999) +
            '" data-source="' + (data.source || 2) +
            '" data-city="' + data.city +
            '" data-district="' + data.district +
            '" data-name="' + data.name +
            '">' + data.name +
            '<span class="city-district">' + data.city + data.district + '</span>' +
            '</li>';
    }

    /**
     *  渲染街道列表下拉框
     * @param params 联想参数
     */
    function renderStreetSelect (params) {
        $('#suggestPanel ul').html('<li class="loading tip">加载中</li>');
        fetchSuggestedStreet(params, function (data) {
            var htmlStr = '';

            if (data.length) {
                $.each(data, function (index, item) {
                    htmlStr += createfetchSuggestedItemHtmlStr(item);
                });
            } else {
                htmlStr += '<li class="non-data tip">无匹配项</li>';
            }

            layer.open({
                area: ['0', '0'],
                shade:  [0.1, '#fff'],
                offset: ['100000px', '100000px'],
                scrollbar: false,
                zIndex: 888,
                success: function (layero, index) {
                    $('#layui-layer-shade' + index).on('click', function () {
                        $(layero).find('.layui-layer-close').trigger('click');
                    });
                },
                cancel: function () {
                    $('#suggestPanel').hide();
                    clearAddress();
                }
            });
            $('#suggestPanel ul').html(htmlStr);
            $('#suggestPanel').show();
            // form.render('select');

            // $('#street-wrapper').find('.layui-form-select').addClass('layui-form-selected');
            // $('#street-wrapper').find('input').val(queryText).focus();
        });
    }

    /**
     * 检查是否平台直派
     * @param plat
     * @param cityId
     * @param bizType
     */
    function checkGrid(cityId){
        // 返修单不显示校验服务商
        if(!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK){
            return;
        }
        $http.$get(IS_GRID, {
            platWork:getters.getPlatWork(),
            cityId: cityId,
            bizType:getters.getBizType()
        }).then(function (data) {
            if (data==20){
                $("#preCompany").text('校验服务商');
            } else {
                $("#preCompany").text('');
            }
        }, function (msg) {
            layer.msg('网络错误');
        });
    }

    /**
     * 设置表单字段值
     * @param {object} values 表单值对象
     */
    function setFieldsValue (values) {
        layui.form.val('zmn-order-add-form', values);
    }

    /**
     * 初始化预约时间相关时间
     * @param {string} time 时间
     */
    function initDutyTimeInfo (showTime,time) {
        $('#duty-time-input').val(time);
        $('#duty-time').text(showTime);
    }

    /**
     * 初始公司信息
     */
    function initCompanyInfo () {
        var plat = getters.getPlatWork();
        var channelId = getters.getChannelId();
        var cityId = getters.getCityId();
        var countyId = getters.getCountyId();
        var type = getters.getOrderType();
        var dutyTime = getters.getDutyTime();
        var workId = getters.getWorkId();
        var bizType = getters.getBizType();
        var servCategId = getters.getServCategId();
        var productShowType = getters.getProductShowType();
        var productId = getters.getProductId();
        var longitude = getters.getLongitude();
        var latitude = getters.getLatitude();
        var streetSource = getters.getStreetSource();

        // 返修单修改，不初始化公司信息
        if(!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK){
            setCompanyInfo($('#hidCompany').val());
            return;
        }

        if (!plat || !productId || (!longitude && !countyId)) {
            setCompanyInfo('');
        } else {
            fetchCompanyName(plat, channelId, cityId, countyId, type, dutyTime, workId, bizType, servCategId, productShowType, productId, longitude, latitude, streetSource).then(function (res) {
                if (!res) {
                    setCompanyInfo('<span style="color: red">当前平台无法服务，其他平台也无法服务</span>')
                } else if (res.data == 3) { // 转其他平台服务
                    setCompanyInfo('<span style="color: #FE8514">' + res.message + '</span>')
                } else if (res.data == 0) {// 所有平台都无法服务
                    setCompanyInfo('<span style="color: #FF0000">' + res.message + '</span>')
                } else {
                    setCompanyInfo(res.message || '')
                }
            });
        }
    }

    /**
     * 计算产品价格
     */
    function calculateProductAmount () {
        var servCategId = getters.getServCategId();

        var count = getters.getCount();
        var cityId = getters.getCityId();
        var factoryId = getters.getFactoryId();
        var bizType = getters.getBizType();
        var productId = getters.getProductId();
        var channelId = getters.getChannelId();

        if (!servCategId || !count || !cityId || !productId || !channelId) {
            $('#amount-wrapper').hide();
            $('#amount').val('');
            return;
        }

        $('#amount-wrapper').show();

        showToatlAmountDiv(servCategId, count, cityId, productId, channelId, bizType);
    }

    /**
     * 判断是否是计价器类型的工单，如果是，显示amount-fault如果不是，显示amount-others
     */
    function showToatlAmountDiv(servCategId, count, cityId, productId, channelId, bizType) {
        var plat = getters.getPlatWork();
        var type = getters.getOrderType();
        var orderId = options.isUpdate ? getters.getOrderId() : null;
        var workId = options.isUpdate ? getters.getWorkId() : null;
        var params = {
            cityId: cityId,
            productId: productId,
            channelId:channelId,
            bizType: bizType,
            plat: plat,
            productShowType: getters.getProductShowType(),
            brandId: getters.getBrandId(),
            type: type,
            orderId: orderId,
            workId: workId
        };

        // 目前只支持啄木鸟
        $http.$get(GET_SERVITEM_TYPE_INFO_WORK_URL, params).done(function(data) {
            // 计价器类型工单
            $('#servItemType').val(data.servItemType);
            if (type == '2') {
                $('#amount-others').hide();
                $('#amount-quotation').hide();
            } else {
                if (data.servItemType == "1") {
                    $('#amount-others').show();
                    $('#amount-quotation').hide();
                } else if (data.servItemType == "2") {
                    $('#amount-others').hide();
                    $('#amount-quotation').show();
                }
            }

            if ( data.isShow === 1 ) {
                $('#amount-detail').hide();
            } else if (zmnUtils.isNumber(data.price) && data.unit) {
                $('#amount-detail').show();
                var str = data.price / 100 + '' + '元/'+ data.unit;
                $('#amount').text(str);
            } else if (zmnUtils.isNumber(data.price)) {
                $('#amount-detail').show();
                var str = data.price / 100 + '' + '元';
                $('#amount').text(str);
            }else{
                $('#amount-detail').hide();
            }
        }).fail(function (msg) {
            layer.msg(msg);
        });

    }


    var formUtils = {
        normalizeDutyTime: function (dateStr) {
            return util.toDateString(new Date(dateStr));
            // return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
        },
        normalizeFaults: function (data) {
            var faultArray = data.filter((item) => {
                return item.name === 'faultIdList';
            }).reduce((acc, curr) => {
                acc.push(curr.value);
                return acc;
            }, []);

            return faultArray;
        },
        _emptyValueFilter: function (data) {
            var params = {};

            Object.keys(data).forEach((key) => {
                if (data[key] == null || data[key] === '') {
                    return;
                }
                params[key] = data[key];
            });

            return params;
        },
        normalize: function (data) {
            var params = {};
            var excludeArr = ['faultIdList', 'factoryId', 'fcProductId', 'number', 'faultRemark'];

            var field = data.field;
            var formData = $(data.form).serializeArray();

            // 如果streetid为null 就把queryCommunity 接口里的 communityId 赋值给 streetId
            if (!field.streetId) {
                field.streetId = $('#communityId').val();
            }

            Object.keys(field).forEach((key) => {
                if (excludeArr.indexOf(key) === -1) {
                    params[key] = field[key];
                }
            });

            if (field.nextContactDate) {
                params.nextContactTime = field.nextContactDate + ' ' + field.nextContactTime;
            }

            params.orderFactory = {
                factoryId: field.factoryId,
                fcProductNumber: field.number,
                remark: field.faultRemark,
                faultIdList: this.normalizeFaults(formData),
                productId: field.productId
            };

            if (params.dutyTime) {
                params.dutyTime = this.normalizeDutyTime(params.dutyTime);
            }

            return this._emptyValueFilter(params);
        }
    }

    /**
     * 省份选择下拉框选中事件处理函数
     * @param provinceId 省份 id
     */
    function handleProvinceSelect(provinceId) {
        // 更新下拉框选项状态
        updateOptionsStatus($('#provinceId'));

        // 渲染城市下拉框
        initCitySelect(provinceId, getters.getChannelId(), function () {
            renderServCategorySelect(function(){
                // 基础产品
                initProduct(getters.getPlatWork(), getters.getChannelId(), getters.getCityId(), getters.getServCategId(), getters.getBizType());

                // 计算价格
                calculateProductAmount();
            });
        });

        // 清空区域列表
        renderServiceArea([]);

        // 清空街道信息
        renderStreetIdSelect([]);

        // 清空地址
        clearAddress();

        initCompanyInfo();
    }

    /**
     * 城市选择下拉框选中事件处理函数
     */
    function handleCitySelect(cityId) {
        var $city = $('#cityId');

        renderServCategorySelect(function(){
            // 基础产品
            initProduct(getters.getPlatWork(), getters.getChannelId(), cityId, getters.getServCategId(), getters.getBizType());

            // 计算价格
            calculateProductAmount();
        })


        // 更新下拉框选项状态
        updateOptionsStatus($city);

        // 初始化服务区域
        initServiceArea(cityId);
        // 清空地址
        clearAddress();

        // 清空街道信息
        renderStreetIdSelect([]);

        initCompanyInfo();
    }

    function verifyStreetValidation (params) {
        params.type = getters.getOrderType();
		params.add = options.isNew ? 2 : 1;
		return $http.get(STREET_VALIDATION_URL, params).then(function (data) {
            if (data.status !== 2) {
                return $.Deferred().reject('所选地址不在服务范围');
            }
            var $city = $('#cityId option[value="' + data.cityId + '"]');

            if (!$city[0]) {
                return $.Deferred().reject('所选地址与所选城市不匹配');
            }

            return data;
        });
    }

    /**
     *  标准需要查询的城市名称
     * @param cityName 城市名称
     * @returns {String}
     */
    function normalizeCityName (cityName) {
        return cityName.replace('辖县', '').replace('辖区','');
    }

    /**
     * 获取城市名称
     * @returns {String} 城市名称
     */
    function getSelectedCityName () {
        return normalizeCityName($('#cityId option:selected').text());
    }

    /**
     * 分点城市切换主城市
     * @returns {String} 城市名称
     */
    function switchCity (cityId) {
        var $cityId = $('#cityId');
        $cityId.val(cityId);
        form.render('select');

        updateOptionsStatus($cityId);
    }

    /**
     * 更新 区域列表
     * @param countyId 区域 Id
     */
    function updateAreaList (countyId) {
        var $areaItems =$("#county-list span");
        $areaItems.removeClass('current');
        if (!countyId) {
            return;
        }

        $areaItems.filter('[data-id="' + countyId + '"]').addClass('current');
    }

    /**
     * 更新区域输入框的值
     * @param countyId 区域 Id
     */
    function updateAreaInput (countyId) {
        $("#countyId").val(countyId);
    }

    /**
     * 更新区域备注值
     * @param countyName 区域名称
     */
    function updateCountyName (countyName) {
        var $areaItems =$("#county-list span");
        $areaItems.removeClass('current');
        if (!countyName) {
            return;
        }

        $areaItems.filter('[data-name="' + countyName + '"]').addClass('current');
    }

    /**
     * 更新区域相关信息
     * @param countyId 区域 Id
     */
    function updateAreaInfo (countyId) {
        updateAreaList(countyId);
        updateAreaInput(countyId);
        // updateCountyName(countyName);
    }

    /**
     * 更新服务坐标信息
     * @param lnt 经度
     * @param lat 纬度
     */
    function updateLocationInfo (lnt, lat) {
        $('#longitude').val(lnt);
        $('#latitude').val(lat);
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function updateStreetInfo (value) {
        $('#customerAddress').val(value);
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function setStreetSource(value) {
        $('#streetSource').val(value);
    }

    function setStreetId(value) {
        $('#communityId').val(value);
    }

    function updateDistrict (value) {
        $('#district').val(value);
        updateCountyName(value);
    }

    function setUserName (name) {
        $('#username').val(name);
    }

    function setStreetInfo (street) {
        $('#customerAddress').val(street);
    }

    function setAddressInfo (address) {
        $('input[name="address"]').val(address);
    }

    function manualSetSelecteValue (selector, value) {
        var $select = $(selector);
        var $options = $select.find('option:selected');
        $options.attr('selected', false);

        var $option = $select.find('option[value="' + value + '"]');

        if ($option.length) {
            $option.attr('selected', true);
        }
    }

    function setProviceInfo (value) {
        $('input[name="provinceId"]').val(value);
        manualSetSelecteValue('#provinceId', value);
    }
    function setCityInfo (value) {
        $('input[name="cityId"]').val(value);
        manualSetSelecteValue('#cityId', value);
    }

    function setGender (sex) {
        var $checkboxList = $('input[name="gender"]');

        $checkboxList.filter('checked').attr('checked', false);

        $checkboxList.filter('[value="' + sex + '"]').attr('checked', true);
    }

    /**
     * 检查服务是否可用
     */
    function checkServiceValidation () {
        var lng = $('#longitude').val();
        var lat = $('#latitude').val();
        var district = $('#district').val();

        var factoryId = getters.getFactoryId();
        var cityId = getters.getCityId();
        var servCategId = getters.getServCategId();
        var productId = getters.getProductId();
        var countyId = getters.getCountyId();

        if (!factoryId) {
            layer.msg('请先选择厂商');
            return;
        } else if (!cityId) {
            layer.msg('请先选择城市');
            return;
        } else if (!servCategId) {
            layer.msg('请先选择服务类型');
            return;
        }

        // 验证所选地址是否在服务范围
        verifyStreetValidation({
            bizType: getters.getBizType(),
            cityId: cityId,
            longitude: lng,
            latitude: lat,
            servCategId: servCategId,
            areaName: district,
            productId, productId,
            countyId: countyId
        }).then(function (data) {
            updateAreaInfo(data.countyId);
            updateLocationInfo(lng, lat);

            // 初始化公司信息
            initCompanyInfo();

        }, function (msg) {
            layer.msg(msg);
            clearAddress();
            updateAreaInfo('');
        });
    }

    /**
     * 检查服务信息完成性
     */
    function checkServiceInfoCompleteness () {
        var lng = $('#longitude').val();
        var lat = $('#latitude').val();
        var customerAddress = $('#customerAddress').val();

        var factoryId = $('#factoryId').val();
        var cityId = $('#cityId option:selected').val();
        var servCategId = $('#servCategoryId option:selected').val();
        var productId = getters.getProductId();

        return lng && lat && customerAddress && factoryId && cityId && servCategId && productId;
    }

    /**
     * 检查百度地图插件是否可用
     * @returns {{msg: string, status: boolean}}
     */
    function checkMapAvailability () {
        var result = {
            status: true,
            msg: ''
        };

        var factoryId = $('#factoryId').val();
        var cityId = $('#cityId option:selected').val();
        var servCategId = $('#servCategoryId option:selected').val();

        if (!factoryId) {
            result = {
                status: false,
                msg: '请先选择厂商'
            };
        } else if (!cityId) {
            result = {
                status: false,
                msg: '请先选择城市'
            };
        }

        return result;
    }

    /**
     * 设置与返修逻辑相关字段状态
     * @param {boolean} disabled 是否禁用
     * @private
     */
    function _setRelativeFieldState (disabled) {
        $('#provinceId').prop('disabled', disabled);
        $('#cityId').prop('disabled', disabled);
        form.render();
    }

    /**
     * 初始化返修原单输入框
     * @param {object} $input 输入框 jQuery 对象
     * @private
     */
    function _initReworkInputEvent ($input) {
        var initRelativeFieldValue = function (data) {
            setFieldsValue({
                provinceId: data.provinceId,
                cityId: data.cityId,
                latitude: data.latitude,
                longitude: data.longitude,
                address: data.address,
                street: data.street
            });
            setCompanyInfo(data.manageCompanyName);
            calculateProductAmount();
            // 初始化区域信息
            initServiceArea(data.cityId, function () {
                updateAreaList(data.countyId);
                setFieldsValue({
                    countyId: data.countyId
                });
            });
            // 初始化街道信息
            handleCountySelect(data.countyId, function () {
                setFieldsValue({
                    streetId: data.streetId
                });
            });
            form.render();
        };

        $input.on('change', function () {
            /**
             * 检查返修工单号
             * 1. 成功：反填信息、禁用省份、城市
             * 2. 失败、提示
             */
            var $input = $(this);
            var reworkId = $.trim($input.val());

            if (reworkId === '') {
                $input.focus();
                zmnUtils.layui.toastError('请填写返修源单号');
                return;
            }

            checkReworkId(reworkId).then(function (data) {
                var productId = getters.getProductId();
                var cityId = getters.getCityId();
                var latitude = getters.getLatitude();
                var longitude = getters.getLongitude();
                var address = getters.getAddress();
                var street = getters.getStreet();

                if (productId || cityId || latitude || longitude || address || street) {
                    layer.alert('返修源单地址将自动覆盖', {
                        skin: 'layui-layer-molv',
                        closeBtn: 0
                    }, function (index) {
                        initRelativeFieldValue(data);
                        layer.close(index);
                    });
                } else {
                    initRelativeFieldValue(data);
                }
            }, function (message) {
                setFieldsValue({
                    reworkId: ''
                });
                $input.focus();
                zmnUtils.layui.toastError(message);
            });
        });
    }

    // 检查原单号
    function checkReworkId (rewordId) {
        var getValue = getters.getInputValueById;

        var params = {
            reworkId: $.trim(rewordId),
            orderId: getValue('order-id'),
            workId: getValue('work-id'),
            productId: getters.getProductId(),
            productShowType: getters.getProductShowType(),
            telephone: getValue('telephone'),
            telephone2: getValue('telephone2'),
            telephone3: getValue('telephone3'),
            cityId: getters.getCityId(),
            longitude: getters.getLocation().lng,
            latitude: getters.getLocation().lat,
            platWork: getters.getPlatWork()
        };

        return $http.$ajax({
            url: CHECK_REWORD_ID_URL,
            type: 'GET',
            data: params,
            async: false
        });
    }

    /**
     * 初始绑定返修原单输入框事件
     */
    (function initReworkInputEvent () {
        var $input = $('input[name="reworkId"]');
        if ($input.length) {
            _initReworkInputEvent($input);
        }
    }());

    /**
     * 设置分公司名
     * @param {string} name 公司名
     */
    function setCompanyInfo (name) {
        $('#company').html(name);
    }

    /**
     * 获取公司信息
     */
    function fetchCompanyName(plat, channelId, cityId, countyId, type, dutyTime, workId, bizType, servCategId, productShowType, productId, longitude, latitude, streetSource) {
        servCategId = servCategId || 0
        productShowType = productShowType || 0
        productId = productId || 0

        var reqData = {
            plat: plat,
            channelId: channelId,
            cityId: cityId,
            countyId: countyId,
            streetId: getters.getStreetId(),
            type: type,
            dutyTime: dutyTime,
            workId: workId,
            bizType: bizType,
            servCategId: servCategId,
            productShowType: productShowType,
            productId: productId,
            longitude: longitude,
            latitude: latitude,
            streetSource: streetSource
        }

        return $http.$get(COMPANY_URL, reqData);
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('input', 'input', function () {
            var $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });

        // 电话号码输入框输入事件
        $('#telephone, #telephone2, #telephone3').on('input', function () {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d\*]/ig, ''));
        });

        //自定义验证规则
        form.verify({
            radio: function (value, item) {
                var $ = layui.$;
                var verifyName = $(item).attr('name')
                    , verifyType = $(item).attr('type')
                    , formElem = $(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                    , verifyElem = formElem.find('input[name=' + verifyName + ']')//获取需要校验的元素
                    , isTrue = verifyElem.is(':checked')//是否命中校验
                    , focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                if (!isTrue || !value) {
                    //定位焦点
                    focusElem.css(verifyType == 'radio' ? {"color": "#ff5722"} : {"border-color": "#ff5722"});
                    //对非输入框设置焦点
                    focusElem.first().attr("tabIndex", "1").css("outline", "0").blur(function () {
                        focusElem.css(verifyType == 'radio' ? {"color": ""} : {"border-color": ""});
                    }).focus();
                    return '必填项不能为空';
                }
            },
            brand: function (value, item) {
                // 品牌验证， 家电安装、家电清洗、家电维修 必选，其它不必须
                var servCategId = getters.getServCategId();
                if ((servCategId == '1001' || servCategId == '1002' || servCategId == '1003') && !value) {
                    return '必填项不能为空';
                }
            }
        });

        // 厂商选择下拉框的点击事件处理器
        form.on('select(factory)', function (data) {
            var factoryId = data.value;

            // 初始化渠道信息
            initChannelId(function(){
                initCitySelect(getters.getProvinceId(), data.value, function(){
                    renderServCategorySelect(function(){
                        // 基础产品
                        initProduct(getters.getPlatWork(), getters.getChannelId(), getters.getCityId(), getters.getServCategId(), getters.getBizType());
                    });
                });
            });

            // 初始化厂商配件信息
            table.reload(factoryPartTableId, {
                data: []
            });

        });

        // 服务类型选择下拉框的点击事件处理器
        form.on('select(servCategory)', function (data) {

            // 计算价格
            calculateProductAmount();

            // 初始化产品数量输入框
            initCountInput(1);

            initProductUnit('');

            // 初始化其他故障文本域
            initOtherFaultsTextarea();

            // 基础产品
            initProduct(getters.getPlatWork(), getters.getChannelId(),  getters.getCityId(), getters.getServCategId(), getters.getBizType());

            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness()) {
                checkServiceValidation();
            }

        });

        // 服务类型选择下拉框的点击事件处理器
        form.on('select(productId)', function (data) {
            // 初始化常见故障多选框组
            initCommonFaultsCheckboxGroup(getters.getProductId());

            var unit = $(data.elem).find('option:selected').data('unit') || '';

            // 初始化产品数量输入框
            initCountInput(1);

            // 初始化产品单位
            initProductUnit(unit);

            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness()) {
                checkServiceValidation();
            }

            // 初始化服务分类
            var serviceGategoryId = $(data.elem).find('option:selected').data('pid');

            if (serviceGategoryId) {
                setFieldsValue({servCategId: serviceGategoryId});
            }

            // 计算价格
            calculateProductAmount();

            // 初始化预约时间
            initDutyTime(function () {
                // 初始化公司信息
                initCompanyInfo();
            });
        });

        // 订单类型单选框的选中事件处理器
        form.on('radio(order-type)', function (data) {
            var value = data.value;
            var $originCode = $('#origin-code');
            var $inputContainer = $originCode.find('.layui-input-inline');

            if (!$inputContainer.length) {
                $inputContainer = $originCode;
            }

            // 判断是否为返修单 1 为新单 2为返修单 3为退款单
            if (value === '2') {

                // 检查电话01和产品
                var telephone = getters.getTelephone();
                var productId = getters.getProductId();

                if (!telephone || !productId) {
                    zmnUtils.layui.toastError('请先填写电话和产品!');
                    setFieldsValue({ type: ORDER_TYPE_ENUM.NEW });
                    return;
                }

                _setRelativeFieldState(true);
                // 添加返修单输入框
                $inputContainer.html('<input class="layui-input" id="reworkId" type="text" name="reworkId" placeholder="请填写返修源单号" autocomplete="off" lay-verify="rework">');
                var $input = $inputContainer.find('input[name="reworkId"]');
                _initReworkInputEvent($input);
                $('#origin-code').removeClass('layui-hide');
                form.render();
            } else {
                // 删除返修单输入框
                $originCode.addClass('layui-hide');
                $originCode.find('input').val('');
                $inputContainer.html('');
                // 解除省份城市禁用
                _setRelativeFieldState(false);

                form.render();
            }

			// 初始化预约时间
			initDutyTime(function () {
                // 初始化公司信息
                initCompanyInfo();
            });

            EventBus.$emit('orderTypeCheck', data);
        });

        // 产品数量输入框的 input 事件、change 事件
        $('#count').on('input', function () {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d]/ig, ''));
        }).on('change', function () {
            // 计算价格
            calculateProductAmount();
        });

        // 省份选择下拉框的点击事件处理器
        form.on('select(province)', function (data) {
            handleProvinceSelect(data.value);
        });

        // 城市选择下拉框的点击事件处理器
        form.on('select(city)', function (data) {
            var cityId = data.value;
            var provinceId = $(data.elem).find('option[value="' + cityId + '"]').data('pid');

            if (provinceId) {
                $('#provinceId').val(provinceId);
                form.render('select');
            }

            handleCitySelect(cityId);

            //是否平台直派
            checkGrid(cityId);
        });

        // 街道输入框输入事件
        (function initStreeInputEvent() {
            var timer = null;
            $('#customerAddress').on('input', function (e) {
                e.preventDefault();
                var $this = $(this);

                clearTimeout(timer);
                timer = setTimeout(function () {
                    var queryStr = $this.val();
                    var cityName = getSelectedCityName();
                    var cityId = getters.getCityId();
                    renderStreetSelect({
                        queryStr: queryStr,
                        cityName: cityName,
                        cityId: cityId,
                        ak: addOrderWebAk
                    });
                }, 300);
            });
        })();

        // 街道输入框获取焦点事件
        $('#customerAddress').on('focus', function (e) {
            var $this = $(this);
            //
            // var result = checkMapAvailability();
            // if (!result.status) {
            //     layer.msg(result.msg);
            //     $this.blur();
            // }
        });

        $('#suggestPanel').on('click', 'li:not(.tip)', function () {
            var $li = $(this);

            // 关闭遮罩层
            layer.closeAll();

            // if (getSelectedCityName() !== $li.data('city')) {
            //     layer.msg("所选地址与所选城市不匹配！");
            //     clearAddress();
            //     return;
            // }

            var lng = $li.data('lng');
            var lat = $li.data('lat');
            var name = $li.data('name');
            var district = $li.data('district');
            var streetSource = $li.data('source');
            var streetId = $li.data('communityid');

            updateLocationInfo(lng, lat);
            updateStreetInfo(name);
            updateDistrict(district);
            setStreetSource(streetSource);
            setStreetId(streetId);

            // 更新区域list
            setCountyInfo(district, lng, lat, function(){
                // 如果前面的信息完整就检查服务服务可用性
                if (checkServiceInfoCompleteness()) {
                    checkServiceValidation({
                        street: name,
                        longitude: lng,
                        latitude: lat
                    });
                }
            });

            $('#suggestPanel').hide();
        });

        // 百度地图按钮点击事件
        $('#btn-map').on('click', function (e) {
            e.preventDefault();

            var result = checkMapAvailability();

            if (!result.status) {
                layer.msg(result.msg);
                return;
            }
            // 处理逻辑
            var cityId = getters.getCityId();
            var servCategId = getters.getServCategId();
            var bizType = getters.getBizType();

            parent.addressOptions = {
                location: getters.getLocation(),
                cityId: cityId,
                servCategId: servCategId,
                productShowType: getters.getProductShowType(),
                productId: getters.getProductId(),
                cityName: getters.getCityName(),
                street: getters.getStreet(),
                streetId: getters.getStreetId(),
                streetSource: getters.getStreetSource(),
                countyId: getters.getCountyId(),
                countyName : getters.getInputCountyName(),
                plat: getters.getPlatWork(),
                verifyFunc: function (selectedAddress, succ_cb, fail_cb) {
                    setCountyInfo(selectedAddress.addressComponents.district, selectedAddress.point.lng, selectedAddress.point.lat, function (countyId) {
                        verifyStreetValidation({
                            bizType: bizType,
                            cityId: cityId,
                            servCategId: servCategId,
                            productShowType: getters.getProductShowType(),
                            productId: getters.getProductId(),
                            longitude: selectedAddress.point.lng,
                            latitude: selectedAddress.point.lat,
                            countyId: countyId,
                        }).then(
                            function (data) {
                                if (cityId != data.cityId) {
                                    switchCity(data.cityId);
                                }
                                succ_cb(data);
                            },
                            function (msg) {
                                fail_cb(msg);
                            }
                        );
                    })
                },
                callBack: function (data, addressObj) {
                    updateAreaInfo(data.countyId);
                    updateStreetInfo(addressObj.address);
                    updateLocationInfo(addressObj.point.lng, addressObj.point.lat);
                    setStreetId(addressObj.communityId);
                    setStreetSource(addressObj.streetSource);

                    // 初始化公司信息
                    initCompanyInfo();
                }
            };

            parent.layer.open({
                title: "选择地址",
                type: 2,
                area: ['90%', '90vh'],
                fix: true, //不固定
                maxmin: false,
                content: OMS_BASE_URL + '/order/addressmap.ation',
                end: function () {
                    $("#customerAddress").focus();
                }
            });
        });

        // 产品相关输入框的 focus 事件
        $('#product-list').on('focus', 'input', function () {
            if (!$('#cityId option:checked').val()) {
                layer.msg('请先选择城市');
                $(this).blur();
            }
        });

        // 查看价格表按钮的点击事件
        $('#btn-price-table').on('click', function (e) {
            e.preventDefault();

            var cityId = getters.getCityId();
            var productId = getters.getProductId();
            var servCategId = getters.getServCategId();
            var channelId = getters.getChannelId();
            var bizType = getters.getBizType();
            var type = getters.getType();
            var plat = getters.getPlatWork();
            var productShowType = getters.getProductShowType();
            var orderId = options.isUpdate ? getters.getOrderId() : null;
            var workId = options.isUpdate ? getters.getWorkId() : null;

            if (!servCategId) {
                layer.msg('请先服务分类');
                return;
            }

            if (!productId) {
                layer.msg('请先选择产品');
                return;
            }

            if (!cityId) {
                layer.msg('请先选择城市');
                return;
            }

            var priceTableURL = zmnUtils.serializeURL(PRODUCT_PRICE_TABLE_URL, {
                cityId: cityId,
                productId: productId,
                channelId: channelId,
                bizType: bizType,
                type: type,
                plat: plat,
                tariffType: 1,
                orderId: orderId,
                workId: workId
            });

            layer.open({
                type: 2,
                title: '价格表',
                content: priceTableURL,
                shade: [0.8, '#393D49'],
                area: ['98%', '96vh']
            });
        });

        // 选择预约时间按钮的点击事件
        $('#btn-duty-time').on('click', function (e) {
            e.preventDefault();

            var layer = parent.layui.layer;

            layer.open({
                title: "选择预约时间",
                type: 2,
                shift: 7,
                area: ['980px', '650px'],
                fix: true,
                offset: ['6px'],
                zIndex: 99999999999,
                content: OMS_BASE_URL + '/order/dutytime',
                success: function (layero, index) {
                    parent.layer.setTop(layero);
                    parent.window.dutyTimeOptions = {
                        dutyTime: getters.getDutyTime(),
                        cityId: getters.getCityId(),
                        plat:getters.getPlat(),
                        platWork:getters.getPlatWork(),
                        productId: getters.getProductId(),
                        workId: getters.getWorkId(),
                        type: getters.getOrderType(),
                        channelId: getters.getChannelId(),
                        confirm: function (time) {
                            initDutyTimeInfo(time,time);
                            // 初始化公司信息
                            initCompanyInfo();
                        }
                    };
                }
            });
        });

        // 预约时间多选框勾选事件
        form.on('checkbox(duty-time-checkbox)', function (data) {
            dutyStatusCheck(data.elem.checked);
        });

        // 保存确认按钮点击事件
        form.on('submit(confirmbtn)', function (data) {
            // 修改校验重复单
            // 保存
            var params = formUtils.normalize(data);
			// 复制工单，需要将platWork->plat
            if (params.isCopy) {
                params.plat = getters.getPlatWork();
            }

            // 新机、物流信息补充
            params.orderPostList = getNewMachineData(newMachineTableId);
            params.orderPartPostList = getFactoryPartData(factoryPartTableId);

            saveOrderInfo(params, data.elem).then(function (data) {
                layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                    zmnUtils.isFunction(options.success)
                        ? options.success(data)
                        :(
                            options.modifyDetail
                                ? goWorkModifyDetail(data.orderWork.orderId, data.orderWork.workId)
                                : goWorkDetail(data.orderWork.orderId, data.orderWork.workId)
                        );
                });
            }, function (msg) {
                layer.msg(msg);
            });

            return false;
        });

        // 区县选择下拉框的点击事件处理器
        form.on('select(countyId)', function (data) {
            var countyId = data.value;

            handleCountySelect(countyId);

            // 服务公司
            initCompanyInfo();
        });

        // 街道选择下拉框的点击事件处理器
        form.on('select(streetId)', function (data) {
            recreatFuzzyInfo();

            // 服务公司
            initCompanyInfo();
        });

        // 精确地址与模糊地址切换
        $("#address-type-exact").on('click', function(e) {
            initFuzzyAddress();
        });

        $("#address-type-fuzzy").on('click', function(e) {
            initExactAddress();
        });

        // 校验服务商的点击事件
        $('#preCompany').on('click', function (e) {
            e.preventDefault();

            var layer = parent.layui.layer;

            // 检查产品
            if (!getters.getProductId()) {
                layer.alert("请选择产品", {offset: "250px"});
                return;
            }

            // 检查城市
            if (!getters.getCityId()) {
                layer.alert("请选择城市", {offset: "250px"});
                return;
            }

            // 检查经纬度
            if (!getters.getLongitude()) {
                layer.alert("请选择经纬度", {offset: "250px"});
                return;
            }

            let plat = getters.getPlatWork();

            let url = OMS_BASE_URL + '/order/check/company.action';
            if ($(document).attr("title") != "快捷下单"){
                url += '?plat=' + plat;
            }

            layer.open({
                title: "校验服务商",
                type: 2,
                shift: 7,
                area: ['780px', '345px'],
                fix: true,
                zIndex: 99999999999,
                content: url,
                success: function (layero, index) {
                    parent.layer.setTop(layero);
                    parent.window.checkCompanyOptions = {
                        workId: getters.getWorkId(),
                        reworkId: $("#reworkId").val(),
                        type: getters.getOrderType(),
                        recommenderId: $("#recommenderId").val(),
                        channelId: getters.getChannelId(),
                        platWork: getters.getPlatWork(),
                        plat: getters.getPlat(),
                        bizType: getters.getBizType(),
                        cityId: getters.getCityId(),
                        productId: getters.getProductId(),
                        longitude: getters.getLongitude(),
                        latitude: getters.getLatitude(),
                        streetId: getters.getStreetId(),
                        countyId: getters.getCountyId()
                    };
                }
            });
        });
    }

    var verifyRules = {
        // 用户电话验证
        tel: function (value, el) {
            value = $.trim(value);

            if (value === '') {
                return;
            }

            let hideTelephone = $(el).data('val');
            if(hideTelephone && value == hideTelephone){
                return;
            }

            if (validate.phone(value) || validate.tel(value)) {
               return;
            }

            return '请正确填写您的电话号码';
        },
        mobile: function (value, el) {
            value = $.trim(value);

            if (value === '') {
                return;
            }

            let hideTelephone = $(el).data('val');
            if(hideTelephone && value == hideTelephone){
                return;
            }

            if (validate.phone(value)) {
                return;
            }

            return '请正确填写您的手机号码';
        },
        // 产品数量
        count: function (value) {
            value = $.trim(value);
            if (!validate.isPosInt(value)) {
                return '请正确填写产品数量';
            } else if (value > 10) {
                return '产品数量的最大值为 10';
            } else {
                return;
            }
        },
        // 检查原单号
        checkReworkId: function (value) {
            if ($('input[name="type"]:checked').val() === '1') {
                return;
            }

            if (!$.trim(value)) {
                return '必填项不能为空';
            }

            var getValue = getters.getInputValueById;

            var params = {
                reworkId: $.trim(value),
                orderId: getValue('order-id'),
                workId: getValue('work-id'),
                servCategId: getters.getServCategId(),
                telephone: getValue('telephone'),
                telephone2: getValue('telephone2'),
                telephone3: getValue('telephone3'),
                cityId: getters.getCityId(),
                longitude: getters.getLocation().lng,
                latitude: getters.getLocation().lat,
                platWork: getters.getPlatWork()
            };

            if (!params.telephone ||
                !params.servCategId ||
                !params.longitude ||
                !params.latitude) {
                return;
            }

            params.orderId = getValue('order-id');

            var flag = false;
            var failMessage;

            $http.$ajax({
                url: CHECK_REWORD_ID_URL,
                type: 'GET',
                data: params,
                async: false
            }).then(function () {
                flag = true;
            }, function (msg) {
                failMessage = msg || '网络错误，请重试';
            });

            if (!flag) {
                return failMessage;
            }

            return;
        },

        // 验证预约时间
        dutyTime: function (value) {
            if (!$("#duty-time-checkbox").is(':checked') && !value) {
				if(getters.getPlatWork()=='1' || getters.getPlatWork()=="3") {
					return;// 言而有信，一步维修不需要预约时间校验
				}
                return '请选择预约时间!';
            }
            return;
        },

        // 验证长度
        maxLengthFactory: function (length) {
            return function (value) {
                if (value.length > length) {
                    return '输入字符超过最大长度，最大长度为：' + length;
                } else {
                    return;
                }
            };
        }
    }

    function dutyStatusCheck(checked) {
        if (checked) {
            $('#duty-time-wrapper').hide();
            $('#duty-fail-code').removeClass('layui-hide');
            $('#next-contact-time').removeClass('layui-hide');

            $('#dutyFailCode').attr('lay-verify','required');
            $('#next-contact-date-input').attr('lay-verify','required');
            $('#next-contact-time-input').attr('lay-verify','required');
            $('#duty-time-input').attr('lay-verify','');

            initDutyTimeInfo('','');
            // 初始化公司信息
            initCompanyInfo();
        } else {
            $('#duty-time-wrapper').show();
            $('#duty-fail-code').addClass('layui-hide');
            $('#next-contact-time').addClass('layui-hide');

            $('#dutyFailCode').attr('lay-verify','');
            $('#next-contact-date-input').attr('lay-verify','');
            $('#next-contact-time-input').attr('lay-verify','');
        }
    }

    function initVerifyRules () {
        form.verify({
            tel: verifyRules.tel,
            mobile: verifyRules.mobile,
            count: verifyRules.count,
            rework: verifyRules.checkReworkId,
            dutyTime: verifyRules.dutyTime,
            maxLenTo500: verifyRules.maxLengthFactory(500),
            maxLenTo300: verifyRules.maxLengthFactory(300)
        });
    }

    /**
     * 清空输入框的值
     */
    function clearInputValue (selector) {
        $(selector).val('');
    }

    /**
     * 清空输入框的值
     */
    function clearSelectValue (selector) {
        var selectedOption = selector + " option:selected";
        $(selectedOption).prop("selected", false);
    }

    /**
     * 清空地址相关数据
     */
    function clearAddress () {
        var inputArray = [
            '#customerAddress',
            '#longitude',
            '#latitude',
            "#communityId",
            "#streetSource"
        ];

        $.each(inputArray, function (index, selector) {
            clearInputValue(selector);
        });

        var selectArray = [
            '#countyId',
            '#streetId'
        ];

        $.each(selectArray, function (index, selector) {
            clearSelectValue(selector);
        });

        form.render('select');
        setTimeout(function () {
            $('#suggestPanel ul').html('');
            $('#suggestPanel').hide();
        }, 300);
    }

    /**
     * 显示模糊地址选择框
     */
    function initFuzzyAddress() {
        var $this = $("#address-type-exact");
        $this.addClass('layui-hide');
        $("#exact-address").addClass('layui-hide');
        $("#address-type-fuzzy").removeClass('layui-hide');
        $("#fuzzy-address").removeClass('layui-hide');
        clearAddress();

        $('#customerAddress').attr('lay-verify','');
        $('#countyId').attr('lay-verify','required');
        $('#streetId').attr('lay-verify','');
    }

    /**
     * 显示精确地址选择框
     */
    function initExactAddress() {
        var $this = $("#address-type-fuzzy");
        $this.addClass('layui-hide');
        $("#fuzzy-address").addClass('layui-hide');
        $("#address-type-exact").removeClass('layui-hide');
        $("#exact-address").removeClass('layui-hide');
        clearAddress();

        $('#customerAddress').attr('lay-verify','required');
        $('#countyId').attr('lay-verify','');
        $('#streetId').attr('lay-verify','');
    }

    /**
     * 初始化精确地址与模糊地址显示
     */
    function initAddressShow(streetId) {
        if (streetId) {
            initFuzzyAddress();
        } else {
            initExactAddress();
        }
    }


    /**
     * 重新生成模糊地址数据
     */
    function recreatFuzzyInfo() {
        var $street = $("#streetId option:selected");
        if ($street) {
            var lon = $street.data('longitude');
            var lat = $street.data('latitude');
            var id = $street.val();
            if (!id == "") {
                if (!lon || !lat) {
                    $street.prop("selected", false);
                    layer.msg("所选街道无经纬度数据，请到基础数据中心完善配置")
                    return;
                }
                $('#longitude').val(lon);
                $('#latitude').val(lat);
                $('#customerAddress').val($street.text());
                $('#streetSource').val(3);

                // 如果前面的信息完整就检查服务服务可用性
                if (checkServiceInfoCompleteness()) {
                    checkServiceValidation();
                }
            }

        }
    }

    /**
     * 区县选择下拉框选中事件处理函数
     */
    function handleCountySelect(countyId, cb) {
        fetchAreaDetailData(countyId).done(function (data) {
            renderStreetIdSelect(data, cb);
        });
    }

    /**
     * 初始化街道显示
     */
    function renderStreetIdSelect(data, cb) {
        var optionHtmlStr = '<option value="">请选择乡镇或街道</option>';

        $.each(data, function (index, street) {
            optionHtmlStr += `<option value="${street.areaId}" data-longitude="${street.longitude}" data-latitude="${street.latitude}">${street.name}</option>`;
        });

        $('#streetId').html(optionHtmlStr);
        form.render('select');

        if (typeof cb === 'function') {
            cb();
        }
    }


    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaDetailData (pId) {
        return fetchAreaDataByParentId(AREA_DETAIL_URL, { parentId: pId });
    }

    function goWorkDetail (orderId, workId) {
        if (orderId !=null && workId !=null){
            window.location.href = objOfURL.workDetail + '?' + zmnUtils.urlEncode({
                orderId: orderId,
                workId: workId
            });
        } else {
            layer.open({
                content: '下单成功！'
                ,btn: ['确认']
                ,yes: function(index, layero){
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                }
                ,cancel: function(){
                    //右上角关闭回调
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                }
            });
        }
    }

    function goWorkModifyDetail (orderId, workId) {
        window.location.href = objOfURL.workModifyDetail + '?' + zmnUtils.urlEncode({
            orderId: orderId,
            workId: workId
        });
    }

    /**
     * 初始化下次联系时间选择框
     */
    function renderNextTimeDatePicker () {
        var datePickerElem = '#next-contact-date-input';
        var timePickerElem = '#next-contact-time-input';
        var nowDate = $(datePickerElem).data('date');
        var nextHour = $(timePickerElem).data('hour');
        var minDate = $(datePickerElem).data('today-available')
            ? nowDate
            : dayjs(nowDate).add(1, 'day').format('YYYY-MM-DD');
        var timePickerInstance;

        laydate.render({
            elem: datePickerElem,
            type: 'date',
            format: 'yyyy-MM-dd',
            min: minDate,
            done: function (value) {
                var minHour = nowDate === value ? nextHour : 8;
                if (!timePickerInstance) {
                    timePickerInstance = laydate.render({
                        elem: timePickerElem,
                        type: 'time',
                        format: 'HH:mm:ss',
                        theme: 'time-hour',
                        min: minHour + ':00:00',
                        max: '18:00:00',
                        btns: ['clear', 'confirm']
                    });
                } else {
                    timePickerInstance.config.min.hours = minHour;
                }

                // 切换时间选择框的验证状态
                if (value) {
                    $(timePickerElem).attr('lay-verify', 'required');
                } else {
                    $(timePickerElem).attr('lay-verify', '');
                }
            }
        });
    }

    /**
     * 初始化订单快递
     */
    function renderNewOrderPost(){
        orderPostTable = table.render({
            elem:'#orderPostTable',
            width:526,
            data:[],
            cols:[[
                { field: 'expressCode', title: '单号', width: '30%', align: "center"},
                { field: 'expressCompany', title: '快递公司', width: '30%', align: "center"},
                { field: 'itemTypeName', title: '类型', width: '20%', align: "center"},
                { title: '操作', align: "center", toolbar: '#btns' }
            ]],
            done:function(){
            },
            even: true
        })

        table.on('tool(orderPostTable)', function (obj) {
            if (obj.event === 'del') {
                var postData = table.cache["orderPostTable"];
                postData.splice(obj.tr.data('index'), 1)//根据索引删除当前行
                orderPostTable.reload({
                    data: postData
                });
            }
        });

        $("#addOrderPost").on('click',function(){
            var expressCode = $("#expressCode").val();
            var expressCompany = $("#expressCompany").val();
            if (zmnUtil.isEmptyNull(expressCode)) {
                layer.msg("请输入快递单号");
                return
            }
            if (zmnUtil.isEmptyNull(expressCompany)) {
                layer.msg("请选择快递公司");
                return
            }

            var postDataList = table.cache["orderPostTable"];
            postDataList.push({
                expressCode: expressCode,
                expressCompanyCode: expressCompany,
                expressCompany:$("#expressCompany option:selected").text(),
                itemType:1,
                itemTypeName:'新机'
            });

            orderPostTable.reload({
                data: postDataList
            });
        });
    }

    /**
     * 初始化新机快递
     */
    function renderNewMachinePost() {
        newMachineTable = table.render({
            elem: '#newMachineTable',
            width: 524,
            toolbar: '#btn-add',
            defaultToolbar: [],
            data: [],
            cols: [[
                {field: 'expressCode', title: '物流单号', width: '30%', align: "center", templet: '#expressCode-2' },
                {field: 'expressCompany', title: '物流公司', width: 200, align: "center", templet: '#expressCompany-2'},
                {field: 'remark', title: '备注', width: '20%', align: "center", templet: '#remark'},
                {title: '操作', align: "center", toolbar: '#btns'}
            ]],
            done: function () {
            },
            even: true
        })

        table.on('toolbar(newMachineTable)', function (obj) {
            if (obj.event === 'add') {

                // table.cache['newMachineTable'] 无法获取input、select的值，需要手动获取
                let newMachineTableData = getNewMachineData(newMachineTableId);

                newMachineTableData.push({
                });

                table.reload('newMachineTable', {
                    data: newMachineTableData
                });

                // 将select的value值选中对应的option
                renderSelectValueToOption(newMachineTableId);

                form.render();
            }
        });

        table.on('tool(newMachineTable)', function (obj) {
            console.log(obj);
            if (obj.event === 'del') {
                obj.del();
            }
        });
    }

    // 手动获取新机物流信息
    function getNewMachineData(tableId) {
        let newMachineData = new Array();

        $.each($('div[lay-id=' + tableId + ']').find('tbody tr'), function (index, item) {
            let $tr = $(item);
            let expressCode = getText($tr, 'input[name=expressCode]');
            let expressCompanyCode = getSelectVal($tr, 'select[name=expressCompany]');
            let expressCompany = getText($tr, 'select[name=expressCompany] option:selected');
            let remark = getText($tr, 'input[name=remark]');
            newMachineData.push({
                expressCode: expressCode,
                expressCompanyCode: expressCompanyCode,
                expressCompany: expressCompany,
                remark: remark
            });
        });
        return newMachineData;
    }

    /**
     * 初始化厂商配件快递
     */
    function renderFactoryPartPost() {
        factoryPartTable = table.render({
            elem: '#factoryPartTable',
            toolbar: '#btn-add',
            width: 786,
            defaultToolbar: [],
            data: [],
            cols: [[
                {field: 'factoryPart', title: '厂商配件', width: '180', align: "center", templet: '#factoryParts' },
                {field: 'number', title: '数量', width: '80', align: "center", templet: '#number-input' },
                {field: 'expressCode', title: '物流单号', width: '140', align: "center", templet: '#expressCode-2' },
                {field: 'expressCompany', title: '物流公司', width: 160, align: "center", templet: '#expressCompany-2'},
                {field: 'postTarget', title: '邮寄对象', width: 160, align: "center", templet: '#post-target'},
                {title: '操作', align: "center", toolbar: '#btns'}
            ]],
            done: function () {
            },
            even: true
        });

        initpartSelectBySelect2();

        table.on('toolbar(factoryPartTable)', function (obj) {
            if (obj.event === 'add') {

                // table.cache['newMachineTable'] 无法获取input、select的值，需要手动获取
                let factoryPartTableData = getFactoryPartData(factoryPartTableId);

                factoryPartTableData.push({
                });

                table.reload(factoryPartTableId, {
                    data: factoryPartTableData
                });

                // 将select的value值选中对应的option
                renderSelectValueToOption(factoryPartTableId);

                form.render();

                initpartSelectBySelect2();
            }
        });

        table.on('tool(factoryPartTable)', function (obj) {
            if (obj.event === 'del') {
                obj.del();
            }
        });
    }

    // 手动获取厂商配件物流信息
    function getFactoryPartData(tableId) {
        let newMachineData = new Array();

        $.each($('div[lay-id=' + tableId + ']').find('tbody tr'), function (index, item) {
            let $tr = $(item);
            let factoryPartId = getSelectVal($tr, 'select[name=factoryPartId]');
            let factoryPartName = getText($tr, 'select[name=factoryPartId] option:selected');
            let number = getText($tr, 'input[name=number]');
            let expressCode = getText($tr, 'input[name=expressCode]');
            let expressCompanyCode = getSelectVal($tr, 'select[name=expressCompany]');
            let expressCompany = getText($tr, 'select[name=expressCompany] option:selected');
            let postTarget = getSelectVal($tr, 'select[name=postTarget]');
            newMachineData.push({
                partId: factoryPartId,
                partName: factoryPartName,
                number: number,
                expressCode: expressCode,
                expressCompanyCode: expressCompanyCode,
                expressCompany: expressCompany,
                postTarget: postTarget,
                applyType: 1
            });
        });
        return newMachineData;
    }

    /**
     * 将select的值选中对应的option
     */
    function renderSelectValueToOption(tableId) {
        $.each($('div[lay-id=' + tableId + ']').find('select'), function (index, item) {
            let selectValue = $(item).attr('value');
            $.each($(item).find('option[value="' + selectValue + '"]'), function (index, option) {
                $(option).attr('selected', 'selected');
            });
        });
    }

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getSelectVal(item, ele) {
        return $(item).find(ele).val();
    }

    /**
     * 使用 Select2 城市
     */
    function initpartSelectBySelect2 () {

        $('.factoryPart').each(function (index) {
            console.log(this);
            select2.initRemote({
                el: this,
                url: GET_FACTORY_PARTS_URL,
                getParams: function (params) {
                    console.log(this);
                    let factoryId = getters.getFactoryId();
                    return {
                        keyWord: params.term,
                        factoryId: factoryId
                    };
                },
                processor: function (data) {
                    return data.map((item) => {
                        item.id = item.value;
                        return item;
                    });
                },
                formatRepo: formatRepo
            });

            let partId = $(this).data('option-value');
            let partName = $(this).data('option-name');

            if (partId && partName) {
                $(this).html( $(this).html() + '<option value="'+ partId +'">'+ partName +'</option>');
                $(this).val(partId).trigger('change');
            }
        });
    }

    /**
     * 格式化城市列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepo (repo) {
        if (repo.loading) {
            return '查询中...'
        }

        var name = repo.text;
        var markup = '<div><div><i class="zmn-icon"></i><span>' + name + '</span></div></div>';

        return markup;
    }

    /**
     * 更多
     */
    function initMoreModal() {
        $('[data-toggle="allModal"]').on('click', function(){
            var that = $('[data-toggle="modal"]');
            console.log(that)
            if (that.hasClass('layui-icon-up')) {
                that.removeClass("layui-icon-up").addClass("layui-icon-down");
            } else {
                that.removeClass("layui-icon-down").addClass("layui-icon-up");
            }

            var targetId = that.data('target');
            if(!targetId){
                return;
            }
            var $target = $(targetId);
            if ($target.hasClass("layui-hide")) {
                $target.removeClass("layui-hide").addClass("layui-show");
            } else {
                $target.removeClass("layui-show").addClass("layui-hide");
            }
        });
    }

    /**
     * 初始化页面
     */
    function initPage() {
        // 初始化页面所有的日期选择器
        layui.use('select2', function (select2Module) {
            select2 = select2Module;
        });

        // 初始化区域信息
        initServiceArea(getters.getCityId(), function () {
            var countyId = $('#countyId').attr('value');
            $('#countyId').val(countyId);
            layui.form.render("select");
            updateAreaList(countyId);
        });

        // 初始化下次联系时间选择框
        renderNextTimeDatePicker();

        // 初始化页面事件
        initEvent();

        // 触发验证会员电话
        $('input[name="telephone"]').trigger("change");
        // 初始化表单验证规则
        initVerifyRules();

        // 更多
        initMoreModal();
        dutyStatusCheck($("#duty-time-checkbox").is(':checked'));

        form.render();

        if(options.isCopy || getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            initDutyTime(function () {
                initCompanyInfo();
            });
        }


        // 加载校验服务商
        if (getters.getCityId()){
            checkGrid(getters.getCityId());
        }
    }

    exports("oms_order_add_common_factory", {
        init: function (ops) {
            options = ops;

            if(options.isNew === true){
                // 新增订单，使用渠道开通的城市
                CITY_URL = '/area/channel/city/list.action';
            }

            // 初始化页面
            initPage();
        },
        getters: getters,
        goDetail: goWorkDetail,
        goModifyDetail: goWorkModifyDetail,
        renderNewOrderPost: renderNewOrderPost,
        renderNewMachinePost: renderNewMachinePost,
        renderFactoryPartPost: renderFactoryPartPost
    });
});